package com.personal.filter;

import com.personal.utils.CurrentHolder;
import com.personal.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 获取到请求路径
        String requestURI = request.getRequestURI();

        //2. 判断是否是登录或注册请求,如果路径中包含/login,说明是登录操作,放行
        if(requestURI.contains("/login")){
            log.info("登录操作,放行...");
            filterChain.doFilter(request,response);
            return;
        }
        if(requestURI.contains("/register")){
            log.info("注册操作,放行...");
            filterChain.doFilter(request,response);
            return;
        }

        //3. 获取请求头中的token
        String token = request.getHeader("token");
        if(token == null){
            //如果token为空,则从authorization中获取token
            token = request.getHeader("authorization");
        }

        //4. 判断token是否存在,如果不存在,说明用户没有登录,返回错误信息(响应401状态码)
        if(token == null || token.isEmpty()){
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return;
        }

        //5. 如果token存在,校验令牌,如果校验失败 -> 返回错误信息(响应401状态码)
        try {
            Map<String, Object> claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            //CurrentHolder,用于存储当前登录用户的id的线程,适用于aop切面编程
            CurrentHolder.setCurrentId(empId);
            log.info("当前登录用户id: {},将其存入ThreadLocal", empId);
        } catch (Exception e) {
            log.info("令牌非法，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return;
        }

        //6. 校验通过，放行
        log.info("令牌合法,放行...");
        filterChain.doFilter(request,response);

        //7. 删除ThreadLocal中的用户数据
        CurrentHolder.remove();
    }
}
